//https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/?envType=daily-question&envId=2024-02-16


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res;
        queue<TreeNode*> q;
        q.push(root);
        int flag = 0;
        while(!q.empty())
        {
            int n = q.size();
            vector<int> tmp;
            for(int i = 0; i < n; i++)
            {
                TreeNode* tm = q.front();
                q.pop();
                if(tm->left) q.push(tm->left);
                if(tm->right) q.push(tm->right);
                tmp.push_back(tm->val);
            }
            if(flag%2) reverse(tmp.begin(), tmp.end());
            res.push_back(tmp);
            flag++;
        }
        return res;
    }
};